<?php
/**
 * @file $HeadURL: imagelibrary.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2014-12-15 下午12:13:39 $
 * @brief 图片库
 */
namespace haibao\cms\data;

use \haibao\frame\data\query\Condition;
use \haibao\cms\model\filter\ImageLibrary as ImageLibraryFilter;
use haibao\frame\data\query\Pager;

class ImageLibrary extends \haibao\cms\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ImageLibrary');
	}
	
	public function getStarIdByImageId($imageId){
	    $sql = 'select Id,Name from ImagePerson where ImageId = %s';
	    $result = $this->query($sql,array($imageId));
	    $personInfo = array();
	    while($row = $result->fetch_assoc()){
	        $personInfo[$row['Id']] = $row['Name'];
	    }
	    return $personInfo;
	}
	
	public function updateImageIsFashionWear($imageId){
	    $sql = 'update `ImageLibrary` set IsFashionWear = 1 where Id = %s';
	    $this->query($sql,array($imageId));
	}
	
	public function setImageIdsStorage($name,$userId,$ids){
		$cache = new \haibao\cms\cache\ImageLibrary();
	
		$cache->setImageIdsStorage($name,$userId,$ids);
	}
	
	public function getImageIdsStorage($name,$userId){
		$cache = new \haibao\cms\cache\ImageLibrary();
	
		return $cache->getImageIdsStorage($name,$userId);
	}
	
	public function setWapImageIdsStorage($name,$userId,$ids){
	    $cache = new \haibao\cms\cache\ImageLibrary();
	
	    $cache->setWapMarkImageList($name,$userId,$ids);
	}
	
	
	public function getWapImageIdsStorage($name,$userId){
	    $cache = new \haibao\cms\cache\ImageLibrary();
	    return $cache->getWapMarkImageList($name,$userId);
	}

	public function getImageSourceNames(){
		$cache = new \haibao\cms\cache\ImageLibrary();
		$sources = $cache->getImageSourceNames();
		if(!$sources){
			$sql = "select * from ImageSource where Status = 0";
			$result = $this->query($sql);
			while($result->fetch_assoc()){
				$sources[$result->getData('Id')] = $result->getData('Name');
			}
			$cache->setImageSourceNames($sources);
		}
		return $sources;
	}
	/**
	 * 
	 * @param $filter \haibao\cms\model\filter\ImageSphinxDb
	 * @return multitype:
	 */
	public function searchImagesByKeyword($filter){
		$data = array();
		$imageSengine = new \haibao\cms\sengine\ImageSphinxDb();
		$result = $imageSengine->search($filter);
		
		if (!empty($result['matches'])){
			$pager = new Pager();
			$pager->setResultCount($result['total']);
			$filter->setPager($pager);
			foreach ($result['matches'] as $match){
				array_push($data,$match['attrs']);
			}
		}
		
		return $data;
	}
	
	/**
	 * 设置海报聚焦的显示图片
	 * @param unknown $imageIds
	 */
	public function setFocusShow($infoId,$imageIds,$InfoType){
		$infoId = (int)$infoId;
		$delSql = "delete from FocusImage where InfoId=%s";
		$this->query($delSql,array($infoId));
		if($imageIds){
			$imageIds = explode(",", $imageIds);
			$addSql = 'insert into `FocusImage` (InfoId,ImageId,InfoType) values(%s,%s,%s)';
			$updateSql = 'update `FocusImage` set PicUrl=%s where infoId=%s and ImageId=%s';
			$picUrlArr = $this->getImageUrlById($imageIds);
			foreach ($imageIds as $imageId){
				$this->query($addSql,array($infoId,$imageId,$InfoType));
				$this->query($updateSql,array($picUrlArr[$imageId],$infoId,$imageId));
			}
		}
		return true;
	}
	
	public function getImageTagsById($imageId){
		$data = array();
		$sql = 'select TagId from ImageTag where ImageId = %s';
		$result = $this->query($sql,array($imageId));
		$tagIds = array();
		while ($row = $result->fetch_assoc()){
			array_push($tagIds,$result->getData('TagId'));
		}
		
		if ($tagIds){
			$tagData = new \haibao\cms\data\Tag();
			$data = $tagData->getTagsById($tagIds);
		}
		
		return $data;
	}

	public function getImageTagsByImageIds($imageIds){
		$data = array();
		$imageStr = implode(',',$imageIds);
		$sql = 'select ImageId,TagId from ImageTag where ImageId in ('.$imageStr.')';
		$result = $this->query($sql);
		$tagIds = array();
		$imageTags = array();
		while ($row = $result->fetch_assoc()){
			array_push($tagIds,$result->getData('TagId'));
			$imageTags[$result->getData('ImageId')][$result->getData('TagId')] = $result->getData('TagId');
		}

		if ($tagIds){
			$tagData = new \haibao\cms\data\Tag();
			$data = $tagData->getTagsById(array_unique($tagIds));
		}

		foreach($imageTags as $key=>$value){
			foreach($value as $k=>$v){
				if(isset($data[$v]['TagName'])){
					$imageTags[$key][$k] = $data[$v]['TagName'];
				}
			}
		}

		return $imageTags;
	}
	
	public function getImageLibraryByQuery($query){
		$this->initNewDB();
		return $this->getAll($query);
	}
	
	/**
	 * 是否存在子分类
	 * @param int $id
	 */
	public function isExitstChildCategory($id){
		$sql = "select * from `ImageCategoryDefine` where ParentId=%s";
		$result = $this->query($sql, array(intval($id)));
		$data = array();
		while ($row = $result->fetch_assoc()){
			$model = new \haibao\cms\model\data\Tag();
			$model->loadArray($row);
			array_push($data, $model);
		}
		return count($data);
	}
	
	public function addImageToCms($images){
		if(!$images){
			return false;
		}
		$model = new \haibao\cms\model\data\ImageLibrary();
		$idArray = array();
		foreach($images as $key=>$val){
			$model->Filename = $val->Filename;
			$model->Width = $val->Width;
			$model->Height = $val->Height;
			$model->Source = 0;
			$model->UpSource = $val->UpSource;
			$model->EventId = 0;
			$model->Description = $val->Description;
			$model->CreateBy = $val->CreateBy;
			$model->CreateTime = $val->CreateTime;
			$model->Status = $val->Status;
			$model->PicId = 0;
			$model->Editor = 0;
			$this->add($model);
			array_push($idArray,$model->Id);
		}
		return $idArray;
	}
	
	/**
	 * 通过图片id得图片地址
	 * @param $imageId
	 * @return array($imageId=>$url)
	 */
	public function getImageUrlById($imageIds){
		$imageList = array();
		$query = new \haibao\cms\model\filter\ImageLibrary();
		$query->select(array(ImageLibraryFilter::CONDITION_FIELD_NAME_ID,
							 ImageLibraryFilter::CONDITION_FIELD_NAME_FILENAME
				));
		$imageUrl = array();
		if(is_array($imageIds)){
			$query->where(\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_ID, Condition::CONDITION_IN, $imageIds);
			$imageList = $this->getAll($query);
			if($imageList){
				foreach($imageList as $image){
					$imageUrl[$image->Id] = $image->Filename;
				}
			}
		} else {
			$query->where(\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_ID, Condition::CONDITION_EQUAL, $imageIds);
			$imageList = $this->getOne($query);
			if($imageList){
				$imageUrl[$imageList->Id] = $imageList->Filename;
			}
		}
		
		return $imageUrl;
	}
	public function getImageById($imageId){
		$imageId = (array)$imageId;
		
		$query = new \haibao\cms\model\filter\ImageLibrary();
		$query->where(\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_ID, Condition::CONDITION_IN, $imageId);
		
		return $this->getAll($query);
	}
	
	/**
	 * 存数据库
	 * @param string $file
	 * @param string $storagePath
	 * @param int $userId
	 * @param int $upSource
	 * @param boolean $isTemp 是否临时
	 * @return int picId 图片id
	 */
	public function saveImage($file, $storagePath, $userId, $upSource,$userName, $isTemp=true){
		$status = \haibao\cms\model\data\ImageLibrary::STATUS_DISABLE;
		if (!$isTemp){
			$status = \haibao\cms\model\data\ImageLibrary::STATUS_ENABLE;
		}
		
		$fileId = '';
		$id =  $this->saveImageToMysql($file, $storagePath, $fileId, $userId, $status, $upSource,$userName);
		
		/* $fileId = $this->saveImageToMongoDB($file, $storagePath, $status);
		if($fileId){
			$id =  $this->saveImageToMysql($file, $storagePath, $fileId, $userId, $status, $upSource,$userName);
		} */
		
		return $id;
	}
	
	/**
	 * 保存水印地址
	 */
	public function saveWatermarkUrl($url){
	    $cache = new \haibao\cms\cache\ImageLibrary();
	    $cache->saveWatermarkUrl($url);
	}
	
	/**
	 * 取水印地址
	 */
	public function getWatermarkUrl(){
	    $cache = new \haibao\cms\cache\ImageLibrary();
	    return $cache->getWatermarkUrl();
	}
	
	/**
	 * 更新MongoDB中的图片信息
	 * @param string $fileId MongoId
	 * @param string $fileName 新图片路径
	 */
	public function updateImageMongoDB($fileId, $fileName){

		$imageContent = file_get_contents('..'.$fileName);
		$data = new \haibao\cms\data\ImageLibraryMongo();
		$data->updateImage($fileId, $fileName,$imageContent);
		return $fileId;
	}
	
	/**
	 * 修改MySQL和MongoDB中的数据状态
	 * @param \haibao\cms\model\data\ImageLibrary $model
	 */
	public function updateImageLibrary($model){
		$this->beginTranscation();
		try {
			$id = (array)$model->Id;
			$str = preg_replace('/(\d+)/', '%s', implode(',', $id));
			$arrWhere = $aParam = array();
			if($model->PicId){
				array_push($arrWhere, 'PicId=%s');
				array_push($aParam, $model->PicId);
			}
			if($model->Filename){
				array_push($arrWhere, 'Filename=%s');
				array_push($aParam, $model->Filename);
			}
			if($model->Width && $model->Height){
				array_push($arrWhere, 'Width=%s');
				array_push($arrWhere, 'Height=%s');
				array_push($aParam, $model->Width);
				array_push($aParam, $model->Height);
			}
			if($model->Source){
				array_push($arrWhere, 'Source=%s');
				array_push($aParam, $model->Source);
			}
			if($model->RealSourceId){
				array_push($arrWhere, 'RealSourceId=%s');
				array_push($aParam, $model->RealSourceId);
			}
			if($model->UpSource){
				array_push($arrWhere, 'UpSource=%s');
				array_push($aParam, $model->UpSource);
			}
			array_push($arrWhere, 'EventId=%s');
			array_push($aParam, $model->EventId);
			
			array_push($arrWhere, 'Description=%s');
			array_push($aParam, $model->Description);
	
			if(!$model->IsEdit){
				array_push($arrWhere, 'Editor=%s');
				array_push($aParam, $model->Editor);
			}
			$status = $model->Status ? $model->Status : \haibao\cms\model\data\ImageLibrary::STATUS_ENABLE;
			array_push($arrWhere, 'Status=%s') && array_push($aParam, $status);
			
            if($model->IsWater != null){
                array_push($arrWhere, 'IsWater=%s');
                array_push($aParam, $model->IsWater);
            }
            if($model->Level){
                array_push($arrWhere, 'Level=%s');
                array_push($aParam, $model->Level);
            }
			if(!$id || !$arrWhere){
				return false;
			}
			$sql = 'update `ImageLibrary` set ' . implode(',', $arrWhere) . ' where id in (' . $str . ')';
			$this->query($sql, array_merge($aParam, $id));
			if($status == \haibao\cms\model\data\ImageLibrary::STATUS_PUBLISH && $model->Editor){
				$this->updateImageIndexTime($id);
			}
			
			$data = new \haibao\cms\data\ImageTag();
			if($model->Tags){
				$data->addImageTags($model->Id, explode(',', $model->Tags));
			} else {
				$data->deleteImageTags($model->Id);
			}
			
			$data = new \haibao\cms\data\ImageCategory();
			if($model->CategoryId){
				$data->addImageCategorys($model->Id, explode(',', $model->CategoryId));
			} else {
				$data->deleteImageCategorys($model->Id);
			}
			
			$data = new \haibao\cms\data\ImageBrand();
			if($model->Brands){
				$data->addImageBrands($model->Id, explode(',', $model->Brands));
			} else {
				$data->deleteImageBrands($model->Id);
			}
			
			$data = new \haibao\cms\data\ImagePerson();
			if($model->Persons){
				$data->addImagePersons($model->Id, explode(',', $model->Persons));
			} else {
				$data->deleteImagePersons($model->Id);
			}

			if($model->Editor){
				//入表，准备剪切高400的图
				$filenames = $this->getImageUrlById($id);
				$str = '';
				$arrData = array();
				foreach($filenames as $id=>$filename){
					$str .= '(%s,%s),';
					array_push($arrData,$id);
					array_push($arrData,$filename);
				}
				$sql = 'insert into `ImageTransferCrontab` (`ImageId`,`Filename`) VALUES '.trim($str,',');
				$this->query($sql,$arrData);
			}
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			//$this->updateOldPic($model);
		}
	}
	
	/**
	 * 修改图片库数据状态
	 * @param int or array $id
	 * @param int $status
	 */
	public function updateImageStatus($id, $status = \haibao\cms\model\data\ImageLibrary::STATUS_ENABLE, $userName = ''){
        $id = (array)$id;
		$str = preg_replace('/(\d+)/', '%s', implode(',', $id));
		$sql = 'update `ImageLibrary` set Status=%s where id in (' . $str . ')';
		$aParam = $id;
		array_unshift($aParam, $status);
		$this->query($sql, $aParam);
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			/*
            $sql = 'select UpSource from `ImageLibrary` where Id=%s';
            $result = $this->query($sql, array($id[0]))->fetch_assoc();
            if($result){
                if($result['UpSource'] == \haibao\cms\model\data\ImageLibrary::UPLOAD_SOURCE_IMAGE_LIBRARY){
                    $this->updateOldPicStatus($id, $status, $userName);
                }
            }
            */
		}
	}
	
	/**
	 * 根据图片ID得到图片路径
	 * @param unknown_type $id
	 * @return Ambigous <string, NULL, \DateTime>
	 */
	public function getImageUrl($id){
		$sql = 'select Filename from ImageLibrary where Id='.$id;
		$result = $this->query($sql);
		$imgUrl = '';
		while ($result->fetch_assoc()){
			$imgUrl = $result->getData('Filename');
		}
		return $imgUrl;
	}
	
	public function getImgageByMongo($picId){
		$sql = 'select Filename,PicId from ImageLibrary where Id='.$picId;
		$result = $this->query($sql);
		$imgUrl = '';
		$picId = 0;
		while ($result->fetch_assoc()){
			$imgUrl = $result->getData('Filename');
			$picId = $result->getData('PicId');
		}
		$res = null;
		if($imgUrl && $picId){
			$data = new \haibao\cms\data\ImageLibraryMongo();
			$res = $data->getFileById($picId,$imgUrl);
		}
		
		return $res;
	}
	
	/**
	 * 根据MySQL ID返回Mongo Id和图片存储路径
	 */
	public function getPicIdById($arrId){
		$arrId = (array)$arrId;
		$str = preg_replace('/(\d+)/', '%s', implode(',', $arrId));
		$sql = 'select Filename,PicId from `ImageLibrary` where id in (' . $str . ')';
		$result = $this->query($sql, $arrId);
		
		$data = array();
		while ($result->fetch_assoc()){
			$tmp = array(
				\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_FILENAME => $result->getData('Filename'),
				\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_PICID => $result->getData('PicId'),
			);
			array_push($data, $tmp);
		}
		return $data;
	}
	/**
	 * 公有的由新图片id获取旧图片id
	 * @param $newId array
	 */
	public function publicDataMigrationMapByNewId($newId){
		return self::getDataMigrationMapByNewId($newId);
	}
	
	/**
	 * 保存图片信息到MongoDB中
	 */
	public function saveImageToMongoDB($fileName, $storagePath, $status){
		$imageContent = file_get_contents($fileName);
		$data = new \haibao\cms\data\ImageLibraryMongo();
		$fileId = $data->saveImage($storagePath, $imageContent, array(
				\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_STATUS => $status,
				\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_FILENAME => $storagePath,
		));
		return $fileId;
	}

	public function updateImageIndexTime($imageIds){
		if(is_array($imageIds)){
			$str = implode(',',$imageIds);
			$sql = "update ImageLibrary set IndexTime=%s where Id in (".$str.")";
		} else {
			$sql = "update ImageLibrary set IndexTime=%s where Id = ".$imageIds;
		}
		
		$this->query($sql,array(new \DateTime()));
	}



    public function getImageByFilename($filename){
        $sql = 'select Id from ImageLibrary where Filename=%s limit 1';
        return $this->query($sql, array($filename))->fetch_assoc();
    }

    public function addImageByModel($model){
        self::beginTranscation();
        try{
            parent::add($model);

            if($model->ImageCategory){
                $model->ImageCategory->ImageId = $model->Id;
                $this->add($model->ImageCategory);

            }

        }catch (\Exception $e){
            $this->rollback();
            throw $e;
        }
        $this->endTranscation();
    }

	/**
	 * 保存图片信息到MySQL中
	 */
	private function saveImageToMysql($fileName, $storagePath, $fileId, $userId, $status, $upSource,$userName){
		list($width, $height) = @getimagesize($fileName);
		
		$model = new \haibao\cms\model\data\ImageLibrary();
		$model->Filename = $storagePath;
		$model->Width = (int)$width;
		$model->Height = (int)$height;
		$model->Source = '';
		$model->EventId = '';
		$model->Description = '';
		$model->Status = $status;
		$model->CreateBy = $userId;
		$model->CreateTime = new \DateTime();
		$model->PicId = $fileId;
		$model->UpSource = $upSource;
		$model->Editor = 0;
		$model->Size = ceil(@filesize($fileName)/1000);
		$model->IndexTime = new \DateTime();
		$this->add($model);
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			//$this->addOldPicIndex($model,$userName);
		}
		
		return $model->Id;
	}
	
	

	
	/**
	 * 添加到旧的图片索引表中
	 * @param \haibao\cms\model\data\ImageLibrary $model
	 */
	private function addOldPicIndex($model,$userName){
		$this->initOldDB();
		
		$sql = 'insert into `picsm_pic_index` (width, height, file_name, adddate, user_id) values(%s,%s,%s,%s,%s)';
		$this->query($sql, array(
			$model->Width, $model->Height, ltrim($model->Filename, '/'), $model->CreateTime, $userName
		));
		$picId = $this->getDb()->insert_id;
		$this->query('insert into `picsm_pic_info` (pic_id, adddate, user_id) values(%s,%s,%s)', array($picId, date('Y-m-d H:i:s'), $userName));
		
		if($picId){
			$this->addDataMigrationMap($model->Id, $picId);
		}
		
		$this->initNewDB();
	}
	
	/**
	 * 添加新旧图片id映射数据
	 */
	private function addDataMigrationMap($newId, $oldId){
		$tableName = 'ImageLibrary';
		if($oldId){
			$sql = 'insert into `DataMigrationMap` (`TableName`, `PrimaryKey`, `OldPrimaryKey`) values(%s, %s, %s)';
			$this->initNewDB()->query($sql, array(
				$tableName, $newId, $oldId
			));
		}
	}
	
	/**
	 * 根据新的图片id查询旧的图片id
	 */
	private function getDataMigrationMapByNewId($newId){
		$tableName = 'ImageLibrary';
		$id = (array)$newId;
		$str = preg_replace('/(\d+)/', '%s', implode(',', $id));
		
		$sql = 'select * from DataMigrationMap where TableName=%s and PrimaryKey in ('.$str.')';
		$aParam = $id;
		array_unshift($aParam, $tableName);
		$result = $this->initNewDB()->query($sql, $aParam);
		
		$retArr = array();
		while ($result->fetch_assoc()){
			$tmp['TableName'] = $result->getData('TableName');
			$tmp['PrimaryKey'] = $result->getData('PrimaryKey');
			$tmp['OldPrimaryKey'] = $result->getData('OldPrimaryKey');
			array_push($retArr, $tmp);
		}
		return $retArr;
	}
	
	/**
	 * 更新旧的图片及其详细信息
	 * @param \haibao\cms\model\data\ImageLibrary $model
	 */
	private function updateOldPic($model){
		$this->dealNotExist($model->Id, $model->UserName);
		
		// 根据事件id查询事件名称
		//$eventName = $model->EventId ? \haibao\cms\business\Event::getEventById($model->EventId)->EventName : null;
		$eventName = $model->EventId;
		if ($model->EventId){
			$eventData= new \haibao\cms\data\Event();
			$eventModel = $eventData->getEventById($model->EventId);
			if ($eventModel){
				$eventName = $eventModel->EventName;
			} else {
				$eventName = null;
			}
		}
		
		// 根据来源id查询来源名称
		$sourceName = null;
		if($model->Source){
			$sourceData= new \haibao\cms\data\ImageSource($model->Source);
			$sourceModel = $sourceData->getOneById($model->Source);
			if($sourceModel){
				$sourceName = $sourceModel->Name;
			}
		}
		// 根据标签id查询标签名，以逗号分割
		$tagArr = array();
		if($model->Tags){
			$tagData = new \haibao\cms\data\Tag();
			$tags = $tagData->getTagsById(explode(',', $model->Tags));
			foreach ($tags as $tag){
				array_push($tagArr, $tag['TagName']);
			}
		}
		
		// 根据品牌id查询品牌名，以逗号分割
		$brandArr = array();
		if($model->Brands){
			$brandData = new \haibao\cms\data\Brand();
			$brands = $brandData->getBrandById(explode(',', $model->Brands));
			foreach ($brands as $brand){
				array_push($brandArr, $brand->NameCN ? $brand->NameCN : $brand->NameEN);
			}
		}
		
		// 提取出添加到旧表中的pic_id
		$aMap = $this->getDataMigrationMapByNewId($model->Id);
		$aOldPicId = array();
		foreach($aMap as $map){
			array_push($aOldPicId, $map['OldPrimaryKey']);
		}
		
		// 更改老库的文件名/宽/高
		if($model->Filename){
			$sql = 'update `picsm_pic_index` set file_name=%s,width=%s,height=%s where pic_id=%s';
			$valArr = array_merge(array(ltrim($model->Filename, '/'),$model->Width,$model->Height),$aOldPicId);
			$this->initOldDB()->query($sql, $valArr);
		}
		
		$str = preg_replace('/(\d+)/', '%s', implode(',', $aOldPicId));
		$sql = 'update `picsm_pic_info` set 
				`class_type`=%s,
				`character`=%s,
				`caseinfo`=%s,
				`description`=%s,
				`tag_keyword`=%s,
				`source`=%s,
				`status`=%s,
				`tag_info`=%s,
				`pinpai`=%s where `pic_id` in ('.$str.')';
		$aParam = array(
				$model->CategoryId,
				$model->Persons,
				$eventName,
				$model->Description,
				implode(',', $tagArr),
				$sourceName,
				0,
				implode(',', $tagArr),
				implode(',', $brandArr)
		);
		$aParam = array_merge($aParam, $aOldPicId);
		$this->initOldDB()->query($sql, $aParam);
		
		$this->initNewDB();
	}
	
	private function updateOldPicStatus($id, $status, $userName){
		if(!$id){
			return false;
		}
		$this->dealNotExist($id, $userName);
		
		// 提取出添加到旧表中的pic_id
        $id = (array)$id;
		$aMap = $this->getDataMigrationMapByNewId($id);
		$aOldPicId = array();
		foreach($aMap as $map){
			array_push($aOldPicId, $map['OldPrimaryKey']);
		}
		if($aOldPicId){
			$str = preg_replace('/(\d+)/', '%s', implode(',', $aOldPicId));
			$oldStatus = $status == \haibao\cms\model\data\ImageLibrary::STATUS_ENABLE ? 0 : 1;
			$sql = 'update `picsm_pic_index` set `status`=%s where `pic_id` in ('.$str.')';
			$aParam = $aOldPicId;
			array_unshift($aParam, $oldStatus);
			
			$this->initOldDB()->query($sql, $aParam);
		}
		
		
		$this->initNewDB();
	}
	
	/**
	 * 处理旧表中不存在的数据
	 * @param array $id
	 */
	private function dealNotExist($id, $userName){
		$aMap = $this->getDataMigrationMapByNewId($id);
		
		$aExistNewId = array();
		foreach($aMap as $map){
			array_push($aExistNewId, $map['PrimaryKey']);
		}
		
		$notExistNewId = array_diff((array)$id, $aExistNewId);
		
		// 把没有添加过的添加过去，详细信息可以不必详细，下面还要再做更新
		if($notExistNewId){
			$newModels = $this->getImageById($notExistNewId);
			foreach($newModels as $item){
				$this->addOldPicIndex($item, $userName);
			}
		}
	}
	/**
	 * 获取图片统计列表
	 */
	public function getImageStatisticList($queryArr){
		
		$getCountSql = "select CreateBy,COUNT(DISTINCT a.Id) as CreateCount,SUM(p.IndexPcClickNum+p.IndexMobileClickNum) AS ImageClickCount from ImageLibrary as a LEFT JOIN ImageProperty AS p ON a.Id = p.ImageId where CreateBy !=0 ";
		
		$sql = "select C.CreateBy,C.CreateCount, IFNULL(C.ImageClickCount,0) AS ImageClickCount,IFNULL(EditCount,0) AS EditCount from ";
		$sql .="(";
		if(!empty($queryArr['createBy'])){
			if(is_array($queryArr['createBy'])){
				$getCountSql .= " And a.CreateBy in (".implode(',', $queryArr['createBy']).")";
			} else {
				$getCountSql .= " And a.CreateBy = ".$queryArr['createBy'];
			}
		}
		
		if(!empty($queryArr['publishTimeType'])){
			$publishTimeType = (int)$queryArr['publishTimeType'];
			switch ($publishTimeType){
				case 1:
					$getCountSql .= " And a.CreateTime >= '".date('Y-m-d H:i:s', strtotime('-1 day'))."' And a.CreateTime <= '".date('Y-m-d H:i:s',time())."'";
					break;
				case 2:
					$getCountSql .= " And a.CreateTime >= '".date('Y-m-d H:i:s', strtotime('-7 day'))."' And a.CreateTime <= '".date('Y-m-d H:i:s',time())."'";
					break;
				case 3:
					$getCountSql .= " And a.CreateTime >= '".date('Y-m-d H:i:s', strtotime('-30 day'))."' And a.CreateTime <= '".date('Y-m-d H:i:s',time())."'";
					break;
			}
		}
	
		if(!empty($queryArr['startDate'])){
			$getCountSql .= " And a.CreateTime >= '".$queryArr['startDate']."'";
		}
	
		if(!empty($queryArr['endDate'])){
			$getCountSql .= " And a.CreateTime <= '".$queryArr['endDate']."'";
		}
		$getCountSql.=" And a.Status = 3";
		$getCountSql.=" GROUP BY a.CreateBy";
		$getCountResult = $this->query($getCountSql);
		$listCount = 0;
		if($getCountResult){
			$listCount = $getCountResult->getMysqlResult()->num_rows;
		}
		$sql .=$getCountSql;
		$sql .=") as C LEFT JOIN (select Editor,COUNT(DISTINCT Id) as EditCount from ImageLibrary WHERE Status = 3 GROUP BY Editor HAVING Editor !=0 ) as E  on C.CreateBy = E.Editor ";
	
		$orderStr = " order by C.CreateCount DESC";
		if(!empty($queryArr['orderType'])){
			$orderType = (int)$queryArr['orderType'];
			$orderVal = $queryArr['orderVal'];
			if(empty($orderVal)){
				$orderVal = "";
			} else {
				$orderVal = "DESC";
			}
			switch ($orderType){
				case 1:
					$orderStr = " order by C.CreateCount ".$orderVal;
					break;
				case 2:
					$orderStr = " order by EditCount ".$orderVal;
					break;
				default:
					$orderStr = " order by C.CreateCount ".$orderVal;
					break;
			}
		}
		$sql .= $orderStr;
		if(!empty($queryArr['source'] ) && $queryArr['source'] == 'export'){
			$limit = "";
		}else{
			$limit = " Limit 0,20";
		}
		if(!empty($queryArr['page']) && $queryArr['page'] > 1){
			$startCount = ($queryArr['page'] - 1) * 20 + 1;
			$limit = " Limit ".$startCount.",20";
		}
		$sql .= $limit;
		//echo $sql;exit;
		$result = $this->query($sql);
		$imageList = array();
		$k = 0;
		while($result->fetch_assoc()){
			$imageList[$k]['CreateBy']=$result->getData('CreateBy');
			$imageList[$k]['CreateCount']=$result->getData('CreateCount');
			$imageList[$k]['ImageClickCount']=$result->getData('ImageClickCount');
			$imageList[$k]['EditCount']=$result->getData('EditCount');
			$k++;
		}
		
		return array('Count' =>$listCount,'List'=>$imageList);
	}
	
	private function initNewDB(){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		return $this;
	}
	
	private function initOldDB(){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		return $this;
	}
	
	public function insertCommentPictures($picInfo){
// 		print_r($picInfo);exit;
		
		if(!strpos($picInfo['FileName'], 'jiepai-1/')){
			$picInfo['FileName'] = 'jiepai-1/'.ltrim($picInfo['FileName'],'/');
		}
		
		$sql  = 'insert into ImageLibrary(`Filename`, `Width`, `Height`, `Source`, `UpSource`, `CreateBy`, `CreateTime`, `Status`, `Size`) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)';
		$width = isset($picInfo['width']) ? $picInfo['width'] : 0;
		$height = isset($picInfo['height']) ? $picInfo['height'] : 0;
        $size = isset($picInfo['size']) ? $picInfo['size'] : 0;
		$this->query($sql,array('/'.$picInfo['FileName'], $width, $height, 0, 16, 4, date('Y-m-d H:i:s'), \haibao\cms\model\data\ImageLibrary::STATUS_DISABLE, $size));
		return $this->getDb()->insert_id;
	}
}



/**
 * MongoDB
 */
class ImageLibraryMongo extends \haibao\cms\data\BaseMongoDb{

	/**
	 * 图片存储在MongoDB中的库前缀
	 */
	const DB_PREFIX = 'haibao_image_';

	const DB_COLLECTION_NAME = 'image';

	/**
	 * 要存储的数据库数量
	 */
	const DB_COUNT_DEV = 2;		// 开发环境
	const DB_COUNT = 50;		// 正式环境

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ImageLibraryMongo');
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MONGODB_IMAGE );
	}

	/**
	 * 获取要存储的数据库名
	 * @param string $key 要存储的图片路径
	 * @return string
	 */
	public function getDbName($key){
		return self::DB_PREFIX . $this->getHash($key);
	}

	/**
	 * 根据GridFS返回的id查询
	 * @param string $fsName 表名
	 * @param string $id GridFS返回的id
	 * @return array
	 */
	public function getFileById($id, $imageUrl){
		self::setDBName($imageUrl);
		return parent::getFileById(self::DB_COLLECTION_NAME, $id);
	}
	
	/**
	 * 根据图片存储路径和Mongo ID修改Mongo中存储记录的状态
	 * @param array $fileArr 图片路径和Mongo ID
	 * @param int $status 要修改的状态
	 * @return boolean
	 */
	public function updateStatusById($fileArr, $status){
		if(!$fileArr)
			return false;
		foreach ($fileArr as $file){
			if($file[\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_PICID]){
				self::setDBName($file[\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_FILENAME]);
				$id = $file[\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_PICID];
				parent::updateByFileId(self::DB_COLLECTION_NAME, $id, array(
					\haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_STATUS => $status
				));
			}
		}
	}

	/**
	 * 保存图片二进制流到MongoDB中
	 * @param string $fsName
	 * @param stream $file
	 * @param array $metadata
	 * @return string
	 */
	public function saveImage($imageUrl, $file, $metadata){
		self::setDBName($imageUrl);
		return parent::storeBytes(self::DB_COLLECTION_NAME, $file, $metadata);
	}

	/**
	 * 更新MongoDB中的图片二进制流
	 */
	public function updateImage($fileId, $imageUrl,$imageContent){
		self::setDBName($imageUrl);
		parent::updateFileContentById(self::DB_COLLECTION_NAME, $fileId,$imageContent);
	}
	
	public function getHash($key){
		$hash = crc32($key) >> 16 & 0xffff;
		
		$dbCount = $this->isDev() ? self::DB_COUNT_DEV : self::DB_COUNT;
		return sprintf('%02s',$hash % $dbCount);
	}
	/**
	 * 当前是否是开发环境
	 */
	private function isDev(){
		$domain = \haibao\frame\http\HttpEnvironment::domain();
		return strpos($domain, 'cms.haibao.cn') === false;
	}
	
	private function setDBName($imageUrl){
		parent::setDB($this->getDbName($imageUrl));
	}
	
}